<?php

namespace serv\papi;

use Exception;
use of;
use L;
use helper\StringHelper;

class PurchaseWarehouse
{
    //查询核销单的库存出库批次号  http://ec.com/serv/?c=PurchaseWarehouse&a=query
    public static function query()
    {
        try {
            //对提交过来数据进行校验
            of::work(null);
            $data = file_get_contents('php://input');
            if (empty($data)) {
                of::work(500, '参数不能为空');
            }
            $param = json_decode($data, true);
            if (!is_array($param)) {
                of::work(500, '参数解析出错');
            }
            $array = [];
            //提交的数据格式如 [{"belong":1,"data":[{"sku":"A0000242D-DZJ-KDA","qty":50}, {"sku":"A00046-BRS-485", "qty":30}]}]
            foreach ($param as $v) {
                //库存包含自己的以及公共的
                $belongArr = array_merge([$v['belong']], [of::config('env.PUBLIC_BELONG')]);
                //传过来的SKU数量
                foreach ($v['data'] as $wv) {
                    $qty = $wv['qty'];
                    //从核销单中按先进先出进行处理
                    $sql = "SELECT id, in_no, po_no, purchase_no, sku, sku_name, currency, price, belong, qty, outbound_qty, (qty - outbound_qty) AS total, in_date, sync, status FROM purchase_warehouse WHERE 1
                            AND sku = '{$wv['sku']}'
                            AND belong IN ('".implode("','", $belongArr)."') 
                            AND status = 0;";
                    $result = L::sql($sql, 'purchase');
                    if (!empty($result)) {
                        foreach ($result as $rv) {
                            if ($rv['total'] < $qty) {
                                //则此单全部都要扣除
                                $array[$v['belong']][$wv['sku']][] = $rv;
                                $qty -= $rv['total'];
                            } else {
                                //还有多的，直接返回就是了
                                $array[$v['belong']][$wv['sku']][] = $rv;
                                break;
                            }
                        }
                    }
                }
            }

            //返回符合条件的结果数据
            echo StringHelper::data2json($array, '获取成功', 200);
            //把数据放到消息队列，延后执行，加快接口数据处理的能力
            of::work(true);
        } catch (Exception $e) {
            echo json_encode(of::work($e), JSON_UNESCAPED_UNICODE);
        }
    }
}